const api = require('../../utils/api.js');

Page({
  data: {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    selectedDate: '',
    viewMode: 'day',
    groupedRecords: [],
    records: [],
    dayMainEmotion: '',
    monthMainEmotion: '',
    loading: false
  },

  onLoad: function(options) {
    console.log('emotion-list onLoad options:', options);
    const now = new Date();
    const year = options.year ? parseInt(options.year) : now.getFullYear();
    const month = options.month ? parseInt(options.month) : now.getMonth() + 1;
    const selectedDate = options.selectedDate || '';
    console.log('解析后的参数:', { year, month, selectedDate });
    console.log('selectedDate 类型:', typeof selectedDate);
    console.log('selectedDate 长度:', selectedDate.length);
    this.setData({ year, month, selectedDate });
    this.loadRecords();
  },

  loadRecords: function() {
    const that = this;
    const { year, month, viewMode, selectedDate } = this.data;
    console.log('loadRecords 开始，当前数据:', { year, month, viewMode, selectedDate });
    this.setData({ loading: true });

    api.getEmotionRecordsByMonth(year, month).then(function(res) {
      console.log('API响应:', res);
      that.setData({ loading: false });
      let records = [];
      if (res.status === 'success' || res.code === 200) {
        records = res.data || [];
        console.log('获取到的记录:', records);
        // 为每条记录加avatar
        records.forEach(function(r) {
          r.avatar = that.getEmotionAvatar(r.emotion);
        });

        // 计算本月主要情绪
        let monthEmotionCount = {};
        records.forEach(function(r) {
          if (r.emotion) {
            monthEmotionCount[r.emotion] = (monthEmotionCount[r.emotion] || 0) + 1;
          }
        });
        let monthMainEmotion = '';
        let maxMonthCount = 0;
        for (let k in monthEmotionCount) {
          if (monthEmotionCount[k] > maxMonthCount) {
            monthMainEmotion = k;
            maxMonthCount = monthEmotionCount[k];
          }
        }

        // 计算选中日期的主要情绪
        let dayMainEmotion = '无记录';
        if (selectedDate) {
          const selectedRecords = records.filter(r => {
            if (!r.created_at) return false;
            // 将UTC时间转换为本地时间进行匹配
            let utcDate = new Date(r.created_at);
            let localDate = new Date(utcDate.getTime() + (8 * 60 * 60 * 1000)); // UTC+8
            let recordDate = localDate.toISOString().substr(0, 10);
            return recordDate === selectedDate;
          });
          if (selectedRecords.length > 0) {
            let dayEmotionCount = {};
            selectedRecords.forEach(function(r) {
              if (r.emotion) {
                dayEmotionCount[r.emotion] = (dayEmotionCount[r.emotion] || 0) + 1;
              }
            });
            let maxDayCount = 0;
            for (let k in dayEmotionCount) {
              if (dayEmotionCount[k] > maxDayCount) {
                dayMainEmotion = k;
                maxDayCount = dayEmotionCount[k];
              }
            }
          }
        }

        that.setData({ 
          monthMainEmotion: monthMainEmotion || '无',
          dayMainEmotion: dayMainEmotion
        });

        if (viewMode === 'day') {
          let grouped = {};
          records.forEach(function(r) {
            if (r.created_at) {
              // 将UTC时间转换为本地时间
              let utcDate = new Date(r.created_at);
              let localDate = new Date(utcDate.getTime() + (8 * 60 * 60 * 1000)); // UTC+8
              let d = localDate.toISOString().substr(0, 10);
              if (!grouped[d]) grouped[d] = [];
              grouped[d].push(r);
            }
          });
          
          console.log('分组后的数据:', grouped);
          console.log('选中的日期:', selectedDate);
          console.log('可用的日期键:', Object.keys(grouped));
          
          // 如果有选中的日期，只显示当天的数据（无论有没有记录）
          if (selectedDate) {
            let selectedRecords = grouped[selectedDate] || [];
            console.log('选中日期的记录:', selectedRecords);
            let groupedArr = [{
              date: selectedDate,
              list: selectedRecords
            }];
            console.log('最终设置的 groupedArr:', groupedArr);
            that.setData({
              groupedRecords: groupedArr
            });
          } else {
            // 如果没有选中日期，显示所有日期的数据
          let groupedArr = Object.keys(grouped).sort((a, b) => b.localeCompare(a)).map(date => ({
            date: date,
            list: grouped[date]
          }));
          that.setData({
            groupedRecords: groupedArr
          });
          }
        } else {
          // 月列表模式下，显示所有数据
          that.setData({
            records: records
          });
        }
      } else {
        that.setData({
          groupedRecords: [],
          records: [],
          dayMainEmotion: '无记录',
          monthMainEmotion: '无记录'
        });
        wx.showToast({
          title: year + '年' + month + '月暂无记录',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(function(error) {
      that.setData({ loading: false });
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
  },

  switchToDay: function() {
    this.setData({ viewMode: 'day' }, this.loadRecords);
  },
  
  switchToMonth: function() {
    this.setData({ viewMode: 'month' }, this.loadRecords);
  },

  prevMonth: function() {
    let { year, month, selectedDate } = this.data;
    if (month === 1) {
      year--;
      month = 12;
    } else {
      month--;
    }
    
    // 检查选中日期是否在新月份内
    if (selectedDate) {
      const selectedYear = parseInt(selectedDate.split('-')[0]);
      const selectedMonth = parseInt(selectedDate.split('-')[1]);
      if (selectedYear !== year || selectedMonth !== month) {
        // 如果选中日期不在新月份内，清除选中日期
        this.setData({ year, month, selectedDate: '' }, this.loadRecords);
      } else {
        // 如果选中日期在新月份内，保持选中状态
        this.setData({ year, month }, this.loadRecords);
      }
    } else {
    this.setData({ year, month }, this.loadRecords);
    }
  },

  nextMonth: function() {
    let { year, month, selectedDate } = this.data;
    if (month === 12) {
      year++;
      month = 1;
    } else {
      month++;
    }
    
    // 检查选中日期是否在新月份内
    if (selectedDate) {
      const selectedYear = parseInt(selectedDate.split('-')[0]);
      const selectedMonth = parseInt(selectedDate.split('-')[1]);
      if (selectedYear !== year || selectedMonth !== month) {
        // 如果选中日期不在新月份内，清除选中日期
        this.setData({ year, month, selectedDate: '' }, this.loadRecords);
      } else {
        // 如果选中日期在新月份内，保持选中状态
        this.setData({ year, month }, this.loadRecords);
      }
    } else {
    this.setData({ year, month }, this.loadRecords);
    }
  },

  onCardTap: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/emotion-detail/emotion-detail?id=' + id
    });
  },

  addRecord: function() {
    wx.navigateTo({
      url: '/pages/record/record'
    });
  },

  clearSelectedDate: function() {
    this.setData({ selectedDate: '' }, this.loadRecords);
  },



  // 临时调试函数
  debugDateConversion: function() {
    console.log('=== 日期转换调试 ===');
    const testDate = '2024-01-15T10:30:00.000Z';
    console.log('原始UTC时间:', testDate);
    
    const utcDate = new Date(testDate);
    console.log('UTC Date对象:', utcDate);
    
    const localDate = new Date(utcDate.getTime() + (8 * 60 * 60 * 1000));
    console.log('本地时间Date对象:', localDate);
    
    const localDateStr = localDate.toISOString().substr(0, 10);
    console.log('本地时间字符串:', localDateStr);
    
    console.log('=== 调试结束 ===');
  },

  getEmotionAvatar: function(emotion) {
    if (!emotion) return '/assets/avatars/professional.png';
    if (emotion === '兴奋' || emotion === '满足' || emotion === '开心' || emotion === '高兴') {
      return '/assets/happy.png';
    }
    if (emotion === '自信' || emotion === '平静' || emotion === '愉悦') {
      return '/assets/confident.png';
    }
    if (emotion === '焦虑' || emotion === '悲伤' || emotion === '内疚' || emotion === '共情') {
      return '/assets/sad.png';
    }
    if (emotion === '愤怒' || emotion === '恐惧' || emotion === '失望') {
      return '/assets/angry.png';
    }
    return '/assets/avatars/professional.png';
  }
});